import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

old_al_legion_event_project_api = Blueprint('old_al_legion_event_project_api', __name__)
old_al_legion_event_project_down_api = Blueprint('old_al_legion_event_project_down_api', __name__)
old_al_legion_event_project_sync_api = Blueprint('old_al_legion_event_project_sync_api', __name__)
old_al_legion_event_project_sync_preprocessing_api = Blueprint('old_al_legion_event_project_sync_preprocessing_api', __name__)


@old_al_legion_event_project_api.route('/old_al_legion_event_project', methods=['POST'])
def old_al_legion_event_project():
    params = json.loads(request.data)
    action = params['action']
    project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if action == 'index':
        query = OldAlLegionEventProject.query.order_by('project').all()
        result = []

        for que in query:
            localization = json.loads(que.localization)
            if '1' in localization:
                title = localization['1']['title']
            else:
                title = '未选择doc_id'

            tmp = {
                "project": int(que.project),
                'title': title,
                'remark': str(que.remark)
            }
            result.append(tmp)
        result_data['data']['item'] = result

    elif action == 'clone':
        project_data = OldAlLegionEventProject.query.filter_by(project=project).first()
        new_project_data = OldAlLegionEventProject(
            basic=project_data.basic,
            localization=project_data.localization,
            reward=project_data.reward,
            remark=project_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败"
        else:
            result_data['data']['msg'] = "克隆成功"

    elif action == 'remark':
        remark = str(params['remark'])
        OldAlLegionEventProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
        result_data['data']['msg'] = "备注修改成功"

    elif action == 'delete':
        project_data = OldAlLegionEventProject.query.filter_by(project=project).first()
        db.session.delete(project_data)
        db.session.commit()
        que_project_data = OldAlLegionEventProject.query.filter_by(project=project).first()
        if que_project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败"
        else:
            result_data['data']['msg'] = "删除成功"

    elif action == 'detail':
        query = OldAlLegionEventProject.query.filter_by(project=project).first()
        basic = json.loads(query.basic)
        project = query.project

        if 'top_reward' not in basic:
            basic['top_reward'] = []

        if '_tag' not in basic:
            basic['_tag'] = []

        tmp = {
            "project": project,
            'basic': basic,
            'reward': json.loads(query.reward)
        }
        result_data['data']['item'] = tmp

    elif action == 'doc_id_list':
        doc_file_data = GetDocByFilename('old_legion_event')
        result = []
        for i in doc_file_data:
            result.append({
                'value': int(i),
                'label': f'{i}-{doc_file_data[i]["title"]}'
            })
        return json.dumps(result)

    elif action == 'update_part':
        data = params['data']
        part = params['part']

        if part == 'basic':
            OldAlLegionEventProject.query.filter_by(project=project).update({
                'basic': json.dumps(data)
            })

        elif part == 'goal_reward':
            project_data = OldAlLegionEventProject.query.filter_by(project=project).first()
            reward = json.loads(project_data.reward)
            reward['user_goal_reward'] = data
            project_data.reward = json.dumps(reward)

        elif part == 'rank_reward':
            project_data = OldAlLegionEventProject.query.filter_by(project=project).first()
            reward = json.loads(project_data.reward)
            reward['user_rank_reward'] = data
            project_data.reward = json.dumps(reward)

        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    return jsonify(result_data)


@old_al_legion_event_project_down_api.route('/old_al_legion_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def old_al_legion_event_project_down(is_push):
    result = {}
    query = OldAlLegionEventProject.query.order_by('project').all()

    calc_score = {
        "legion_add_score_type":
            [
                56
            ],
        "user_add_score_type":
            [
                55
            ],
        "user_score_type_list":
            [
                {
                    "division": 350,
                    "doc":
                        {
                            "1": "Kill 350 Enemy's Troop Force within Battlefield Building",
                            "2": "Kill 350 Enemy's Troop Force within Battlefield Building",
                            "3": "Kill 350 Enemy's Troop Force within Battlefield Building",
                            "5": "Kill 350 Enemy's Troop Force within Battlefield Building",
                            "6": "Kill 350 Enemy's Troop Force within Battlefield Building",
                            "7": "击杀350战场建筑驻扎敌人兵力值"
                        },
                    "points": 1,
                    "score_id_map":
                        {
                            "1": 0
                        },
                    "score_type": 57
                },
                {
                    "division": 2500,
                    "doc":
                        {
                            "1": "Kill 2500 Viper's Troop Force",
                            "2": "Kill 2500 Viper's Troop Force",
                            "3": "Kill 2500 Viper's Troop Force",
                            "5": "Kill 2500 Viper's Troop Force",
                            "6": "Kill 2500 Viper's Troop Force",
                            "7": "击杀2500毒蛇兵力值"
                        },
                    "points": 1,
                    "score_id_map":
                        {
                            "4": 0
                        },
                    "score_type": 57
                }
            ]
    }

    for que in query:
        pid = que.project
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        reward = json.loads(que.reward)

        user_goal_reward = []
        for i in reward['user_goal_reward']:
            user_goal_reward.append({
                'reward': RewardToTMysqlNew(i['reward']),
                'target': i['target']
            })
        user_rank_reward = []
        for i in reward['user_rank_reward']:
            user_rank_reward.append({
                'reward': RewardToTMysqlNew(i['reward']),
                'from': i['from'],
                'to': i['to']
            })

        if 'top_reward' in basic:
            top_reward = RewardToTMysqlNew(basic['top_reward'])
        else:
            top_reward = []

        if 'calendar_doc_id' in basic:
            _calendar_doc_id = basic['calendar_doc_id']
        else:
            _calendar_doc_id = 1

        _tag = basic['_tag'] if '_tag' in basic else []

        result[str(pid)] = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 17,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': _calendar_doc_id,
                    'info': _calendar_doc_id
                },
                'reward': top_reward,
                'show_type': 0
            },
            'basic': {
                'event_ui': basic['event_ui']
            },
            'calc_score': calc_score,
            'localization': localization,
            'reward': {
                'result_reward': {
                    'victory': RewardToTMysqlNew(basic['victory_result_reward']),
                    'defeat': RewardToTMysqlNew(basic['defeat_result_reward'])
                },
                'user_goal_reward': user_goal_reward,
                'user_rank_reward': user_rank_reward,
                'match_fail_reward': RewardToTMysqlNew(basic['match_fail_reward'])
            }
        }

    response = DownLoad('legion_event_project', result, is_push)

    return response


@old_al_legion_event_project_sync_api.route('/old_al_legion_event_project_sync/', methods=['GET', 'POST'])
def old_al_legion_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], _reward)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/legion_event_project_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data), flush=True)
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)), flush=True)
        _project = int(i)
        _basic = data[i]['basic']
        _localization = data[i]['localization']
        _remark = str(_project)
        if "1" in _localization:
            if "title" in _localization["1"]:
                _remark = _localization["1"]["title"]
        _basic = {
            'event_ui': data[i]['basic']['event_ui'],
            'victory_result_reward': [],
            'defeat_result_reward': [],
            'match_fail_reward': []
        }
        _reward = {
            'user_goal_reward': [],
            'user_rank_reward': []
        }

        _basic['match_fail_reward'] = RewardShowToDocBonus3(data[i]['reward']['match_fail_reward'], reward_list)
        _basic['defeat_result_reward'] = RewardShowToDocBonus3(data[i]['reward']['result_reward']['defeat'], reward_list)
        _basic['victory_result_reward'] = RewardShowToDocBonus3(data[i]['reward']['result_reward']['victory'], reward_list)
        for j in data[i]['reward']['user_goal_reward']:
            _reward['user_goal_reward'].append({
                'reward': RewardShowToDocBonus3(j['reward'], reward_list),
                'target': j['target']
            })
        for j in data[i]['reward']['user_rank_reward']:
            _reward['user_rank_reward'].append({
                'reward': RewardShowToDocBonus3(j['reward'], reward_list),
                'from': j['from'],
                'to': j['to'],
            })

        new_project_data = OldAlLegionEventProject(
            project=_project,
            basic=json.dumps(_basic),
            localization=json.dumps(_localization),
            reward=json.dumps(_reward),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})


@old_al_legion_event_project_sync_preprocessing_api.route('/old_al_legion_event_project_sync/preprocessing', methods=['GET', 'POST'])
def old_al_legion_event_project_sync_preprocessing():
    with open(STATIC_PATH + '../sync/legion_event_project.json', encoding='utf8') as f:
        data = json.load(f)
    with open(STATIC_PATH + '../sync/legion_event_project_preprocessing.json', 'w', encoding='utf8') as f:
        f.write(json.dumps(data, sort_keys=True))

    return jsonify({'msg': 'finished'})
